package com.jiaz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiaz.entity.CheckIn;
import com.jiaz.entity.Postion;
import com.jiaz.mapper.CheckInMapper;
import com.jiaz.mapper.PostionMapper;
import com.jiaz.service.CheckInService;
import com.jiaz.untils.ResponseBean;
import com.jiaz.untils.constant.VarConstant;
import com.jiaz.vo.QueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author jiajiazi
 * @version 1.0
 * @date 2022/4/24 12:16
 */
@Service
public class CheckInServiceImpl implements CheckInService {

    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private PostionMapper postionMapper;

    private final String[] colors = {
            "rgb(219,27,165)",
            "rgb(16,17,182)",
            "rgb(34,163,71)",
            "rgb(205,53,53)",
            "rgb(49,184,219)",
            "rgb(56,184,172)",
            "rgb(189,173,39)",
            "rgb(17,17,17)"};

    @Override
    public ResponseBean getCheckInList(QueryVo queryVo) {
        if (ObjectUtils.isEmpty(queryVo)) {
            return ResponseBean.error(4008, "参数错误(空值)");
        }
        if (queryVo.getPageNum() == null) {
            queryVo.setPageNum(VarConstant.PAGE_NUM);
        }
        if (queryVo.getPageSize() == null) {
            queryVo.setPageSize(VarConstant.PAGE_SIZE);
        }
        Page<CheckIn> page = new Page<>(queryVo.getPageNum(), queryVo.getPageSize());
        QueryWrapper<CheckIn> queryWrapper = null;
        String key = queryVo.getKey();
        if (StringUtils.hasLength(key)) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.and(q -> q.like("user_id", key).or().like("venue_id", key).or().like("venue_category_name", key));
        }
        Page<CheckIn> checkInPage = checkInMapper.selectPage(page, queryWrapper);
        return ResponseBean.success(checkInPage);
    }

    @Override
    public ResponseBean getCurrentCheckInTrace(double lat, double lon) {
        QueryWrapper<CheckIn> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_id", "lat", "lon")
                .orderByAsc("user_id", "create_time");
        if (lat <= 180 && lon <= 180) {
            queryWrapper.ge("lat", lat - VarConstant.POSTION_FREQ_DISTANT)
                    .ge("lon", lon - VarConstant.POSTION_FREQ_DISTANT)
                    .le("lat", lat + VarConstant.POSTION_FREQ_DISTANT)
                    .le("lon", lon + VarConstant.POSTION_FREQ_DISTANT);
        }
        List<CheckIn> checkInList = checkInMapper.selectList(queryWrapper);
        ArrayList<Map<String, Object>> resList = new ArrayList<>();
        HashMap<String, Object> seconedMap = null;
        ArrayList<double[]> data = null;
        HashMap<String, Object> thiredMap = null;
        if (checkInList == null || checkInList.size() == 0) {
            return ResponseBean.error(40009, "获取数据为空");
        }
        int preUserId = -1;
        Random random = new Random();
        for (CheckIn checkIn : checkInList) {
            if (checkIn.getUserId() != preUserId) {
                if (data != null) {
                    thiredMap.put("color", colors[random.nextInt(8)]);
                    seconedMap.put("lineStyle", thiredMap);
                    seconedMap.put("coords", data);
                    if (data.size() > 1) {
                        resList.add(seconedMap);
                    }
                }
                preUserId = checkIn.getUserId();
                thiredMap = new HashMap<>();
                data = new ArrayList<>();
                seconedMap = new HashMap<>();
            }
            data.add(new double[]{checkIn.getLon(), checkIn.getLat()});
        }
        if (data != null) {
            thiredMap.put("color", colors[random.nextInt(8)]);
            seconedMap.put("lineStyle", thiredMap);
            seconedMap.put("coords", data);
            if (data.size() > 1) {
                resList.add(seconedMap);
            }
        }

        return ResponseBean.success(resList);
    }

    @Override
    public ResponseBean getAllCheckInTrace() {
        return getCurrentCheckInTrace(181, 181);
    }

    // 更新 checkIN 表的venue_id为postion的id
    @Override
    public void updateVenueByBatch() {
        QueryWrapper<Postion> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "venue_id");
        List<Postion> postionList = postionMapper.selectList(queryWrapper);
        checkInMapper.updateVenueByBatch(postionList);

    }

    @Override
    public ResponseBean userDistantCount() {
        QueryWrapper<CheckIn> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_id", "lat", "lon")
                .orderByAsc("user_id", "create_time");
        List<CheckIn> checkInList = checkInMapper.selectList(queryWrapper);
        ArrayList<Integer> count = new ArrayList<>();

        if (checkInList == null || checkInList.size() == 0) {
            return ResponseBean.error(40009, "获取数据为空");
        }
        int preUserId = -1;
        int[] dCount = new int[50];
        double lat = 0, lon = 0;
        Random random = new Random();
        for (CheckIn checkIn : checkInList) {
            if (checkIn.getUserId() != preUserId) {
                preUserId = checkIn.getUserId();
                lat = checkIn.getLat() / 180.0;
                lon = checkIn.getLon() / 180.0;
            } else {
                //ji算放入
                double lat1 = checkIn.getLat() / 180.0;
                double lon1 = checkIn.getLon() / 180.0;
                int d = (int) (2.0 * 6371.0 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat - lat1) / 2.0), 2) + Math.cos(lat) * Math.cos(lat1) * Math.pow(Math.sin((lon - lon1) / 2.0), 2))));
                if (d < dCount.length) {
                    dCount[d]++;
                }
                lat = lat1;
                lon = lon1;
            }

        }
        int end = 0;
        for (int i = dCount.length - 2; i >= 0; i--) {
            if (dCount[i] != 0) {
                end = i;
                break;
            }
        }
        //for (int i = 1; i <= end; i++) {
        //    dCount[i] += dCount[i - 1];
        //}
        if (end != dCount.length - 1) {
            dCount = Arrays.copyOf(dCount, end + 1);
        }

        return ResponseBean.success(dCount);
    }

    public static void main(String[] args) {
        double lat1 = 40.9883317 / 180.0;
        double lon1 = -74.2747664 / 180.0;
        double lat2 = 40.5508525 / 180.0;
        double lon2 = -73.6838252 / 180.0;
        System.out.println(Math.asin(1));

        double pow = Math.pow(Math.sin((lat2 - lat1) / 2.0), 2);
        System.out.println(pow);
        double v = Math.cos(lat2) * Math.cos(lat1) * Math.pow(Math.sin((lon2 - lon1) / 2.0), 2);
        System.out.println(v);
        System.out.println(v + pow);
        double sqrt = Math.sqrt((v + pow));
        System.out.println(sqrt);
        System.out.println(2.0 * 6371.0 * Math.asin(sqrt));
    }

}
